package com.leha.mp.core.services.imp;

import cn.binarywang.wx.miniapp.api.WxMaService;
import com.github.binarywang.wxpay.service.WxPayService;
import com.github.binarywang.wxpay.service.impl.WxPayServiceImpl;
import com.leha.mp.core.config.WxPayConfig;
import com.leha.mp.core.dao.PlMiniappMapper;
import com.leha.mp.core.entity.mybatis.PlMiniapp;
import com.leha.mp.core.entity.mybatis.PlMiniappExample;
import com.leha.mp.core.services.WAppServices;
import me.chanjar.weixin.common.util.http.apache.DefaultApacheHttpClientBuilder;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;

@Service
public class WAppServicesImpl implements WAppServices, InitializingBean {
    @Autowired
    PlMiniappMapper miniappMapper;

    WxPayService payService;
    private HashMap<Integer, WxMaService> gameServices;
    @Override
    public WxMaService getAppMAServices(Integer appId) {
        return gameServices.get(appId);
    }

    @Override
    public WxPayService getPayServices() {
        return payService;
    }

    public com.github.binarywang.wxpay.config.WxPayConfig payConfig() {
        com.github.binarywang.wxpay.config.WxPayConfig payConfig = new com.github.binarywang.wxpay.config.WxPayConfig();
        payConfig.setAppId(WxPayConfig.getAppId());
        payConfig.setMchId(WxPayConfig.getMchId());
        payConfig.setMchKey(WxPayConfig.getMchKey());
        payConfig.setNotifyUrl(WxPayConfig.getNotifyUrl());
        payConfig.setKeyPath(WxPayConfig.getKeyPath());
        payConfig.setTradeType(WxPayConfig.getTradeType());
        return payConfig;
    }
    @Override
    public void afterPropertiesSet() throws Exception {
        gameServices = new HashMap<Integer, WxMaService>();
        List<PlMiniapp> apps = miniappMapper.selectByExample(new PlMiniappExample());
        for(PlMiniapp app: apps) {
            WxMaService wxMaService = new MAppService(app.getAppid(), app.getSecret(),
                    app.getToken(),app.getAeskey(),app.getMsgdataformat());
            gameServices.put(app.getmId(), wxMaService);
        }

        payService = new WxPayServiceImpl();
        payService.setConfig(payConfig());
    }
}
